<?php
namespace app\data\controller\store;

use app\data\model\GoodsAttribute;
use app\data\model\GoodsAttributeRelations;
use app\data\model\GoodsModels as ModelGoodsModels;
use app\data\model\StoreGoods;
use think\admin\Controller;
use think\Collection;
use think\facade\Db;

/**
 * 商品型号管理
 * Class GoodsCate
 * @package app\store\controller
 */
class GoodsModels extends Controller
{
    
     /**
      * @auth true
      */
    public function index(){
        $this->title = '商品型号管理';
        $this->goods_list = Db::table('store_goods')->where('status',1)->field('id,title')->select();
        $query = $this->_query('goods_models')->equal('status,cate_id,is_hot')->like('title')->equal('goods_id');
        $query->order('sort desc,id desc')->page();
    }

    protected function _index_page_filter(&$data)
    {
    
        foreach ($data as &$vo) {
            $vo['goods'] = StoreGoods::where('id',$vo['goods_id'])->find();
        }
       
    }


       /**
     * 禁用商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        $this->_save('goods_models', ['status' => '0']);
    }

    /**
     * 启用商品信息-
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->_save('goods_models', ['status' => '1']);
    }

    public function get_spec_by_goods(){
        $goods_id = $this->request->param('goods_id');
        $goods = StoreGoods::where('id',$goods_id)->find();
        // $cate_id = $this->getTopCategoryId($goods['cate_id']);
        $spec    = GoodsAttribute::where('cate_id',$goods->cate_id)->with(['values'])->select();
        return $this->success('ok',$spec);
    }

    function getTopCategoryId($categoryId)
    {
        // 获取当前分类
        $category = \think\facade\Db::name('store_goods_cate')->where('id', $categoryId)->find();
        
        // 如果分类不存在，返回 null
        if (!$category) {
            return null;
        }

        // 如果已经是顶级分类，直接返回当前 id
        if ($category['parent_id'] == 0) {
            return $category['id'];
        }

        // 递归查找上级分类
        return $this->getTopCategoryId($category['parent_id']);
    }

     /**
      * @auth true
      */
    public function add(){
        $this->title = '添加商品型号';
        $this->goods_list = Db::table('store_goods')->where('status',1)->field('id,title')->select();
        $attributes = GoodsAttribute::with(['values'])->select()->toArray();
        $this->attributes = json_encode($attributes);
        if($this->request->isPost()){
            $data = $this->_vali([
                'goods_id.require'        => '请选择绑定商品!',
                'name.require'            => '型号名称不得为空!',
                'thumb.require'           => '图片不正确!',
                'specs.require'           => '参数不能为空!',
                'sort.require'           => '排序不能为空!',
                'specs.array'            => '参数格式错误!',
            ]);
            Db::startTrans();
            try {
                $modelId  = ModelGoodsModels::create([
                    'goods_id'   => $data['goods_id'],
                    'name'       => $data['name'],
                    'sort'       => $data['sort'],
                    'thumb'      => $data['thumb'],
                ]);
                if (!$modelId) {
                    throw new \Exception('保存商品型号失败');
                }
   
                foreach ($data['specs'] as $spec) {
                    $attributeId = $spec['attribute_id'];
                    $value = $spec['value'];
                    GoodsAttributeRelations::create([
                        'goods_id'     => $modelId->goods_id,
                        'model_id'     => $modelId->id,
                        'attribute_id' => $attributeId,
                        'value'        => $value
                    ]);
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               return $this->error($e->getMessage());
            }
            return $this->success('添加成功');
        }else{
            $this->_form('goods_models', 'form');
        }
    }


    protected function _edit_form_filter(&$data)
    {
        $data['specs'] = GoodsAttributeRelations::where('model_id',$data['id'])->select();
        $goods = StoreGoods::where('id',$data['goods_id'])->find();
        // $cate_id = $this->getTopCategoryId($goods['cate_id']);
        $attributes_arr    = GoodsAttribute::where('cate_id',$goods->cate_id)->with(['values'])->select()->toArray();
        $this->attributes_arr = $attributes_arr;
        $this->attributes = json_encode($attributes_arr);
       
    }

         /**
      * @auth true
      */
      public function edit(){
        $this->title = '添加商品型号';
        $this->goods_list = Db::table('store_goods')->where('status',1)->field('id,title')->select();
        // $attributes_arr = GoodsAttribute::with(['values'])->select()->toArray();
        // $this->attributes = json_encode($attributes_arr);
        // $this->attributes_arr = $attributes_arr;
        if($this->request->isPost()){
            $data = $this->_vali([
                'id.require'             => 'ID不得为空!',
                'goods_id.require'        => '请选择绑定商品!',
                'name.require'            => '型号名称不得为空!',
                'thumb.require'           => '图片不正确!',
                'specs.require'           => '参数不能为空!',
                'sort.require'           => '排序不能为空!',
                'specs.array'            => '参数格式错误!',
            ]);
            Db::startTrans();
            try {
                $modelId  = ModelGoodsModels::find($data['id']);
                if (!$modelId) {
                    throw new \Exception('信息不存在');
                }
                $modelId->goods_id = $data['goods_id'];
                $modelId->name  = $data['name'];
                $modelId->thumb = $data['thumb'];
                $modelId->specs = $data['specs'];
                $modelId->sort = $data['sort'];
                $modelId->save();
                GoodsAttributeRelations::where('model_id',$modelId->id)->delete();
                foreach ($data['specs'] as $spec) {
                    $attributeId = $spec['attribute_id'];
                    $value = $spec['value'];
                    GoodsAttributeRelations::create([
                        'goods_id'     => $modelId->goods_id,
                        'model_id'     => $modelId->id,
                        'attribute_id' => $attributeId,
                        'value'        => $value
                    ]);
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               return $this->error($e->getMessage());
            }
            return $this->success('编辑成功');
        }else{
            $this->_form('goods_models', 'edit');
        }
    }


        /**
     * 删除商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $id = request()->param('id');
        $goods_model = ModelGoodsModels::find($id);
        if (!$goods_model) {
            return $this->error('信息不存在');
        }
        $goods_model->delete();
        GoodsAttributeRelations::where('model_id',$id)->delete();
        return $this->success('删除成功');
    }
}
